package com.util.controller.util;

import cn.hutool.core.util.StrUtil;
import com.itextpdf.text.pdf.BaseFont;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.OutputStream;
@Component
public class HtmlToPdf {


    /**
     * 将HTML转成PD格式的文件。html文件的格式比较严格
     * @param htmlText  html内容
     * @param os   pdf存储文件输出流, 需要调用方关闭流
     * @throws Exception
     */
    public static void htmlToPdf(String htmlText, OutputStream os) throws Exception {
        // <!DOCTYPE html> 没有闭合标签，故删掉
        htmlText = htmlText.replace("<!DOCTYPE html>", StrUtil.EMPTY);
        Document document = Jsoup.parse(htmlText);
        /*手动为一些标签添加闭合*/
        Elements meta = document.getElementsByTag("meta");
        String html = document.html();
        for (Element link : meta) {
            String s = link.outerHtml();
            String s1 = s.replace("/>", ">");
            html = html.replace(s, s1 + "</meta>");
        }
        Elements link1 = document.getElementsByTag("link");
        for (Element link : link1) {
            String s = link.outerHtml();
            String s1 = s.replace("/>", ">");
            html = html.replace(s, s1 + "</link>");

        }
        html = html.replaceAll("<br>", "<br/>");
        html = html.replaceAll("&nbsp", "&#160");

        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocumentFromString(html);
        // 解决中文支持， 注意本地和生产必须有此字体文件
        ITextFontResolver fontResolver = renderer.getFontResolver();
        String currentSystem = System.getProperty("os.name").toLowerCase();
        if("linux".equals(currentSystem)){
            fontResolver.addFont("/usr/share/fonts/chinese/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        }else{
            fontResolver.addFont("C:/Windows/Fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        }

        renderer.layout();
        renderer.createPDF(os);
    }
}
